<template>
    <div class="login">
        <div class="loginBox">
            <div class="boxLeft">
                <img src="../../assets/loginImage.png" alt="" srcset="">
            </div>
            <div class="boxRight">
                <div class="usernameInput">
                    <div class="userImage">
                        <img src="../../assets/username.png" alt="">
                    </div>
                    <div class="username">
                        <el-input v-model="formData.username" style="width: 360px" placeholder="请输入账户" clearable
                            @blur="verifyName" />
                    </div>
                </div>
                <div class="passwordInput">
                    <div class="passwordImage">
                        <img src="../../assets/password.png" alt="">
                    </div>
                    <div class="password">
                        <el-input v-model="formData.password" style="width: 360px" type="password" placeholder="请输入密码"
                            show-password @blur="verifyPsw" />
                    </div>
                </div>
                <div class="passwordInput" v-if="!flag">
                    <div class="passwordImage">
                        <img src="../../assets/password.png" alt="">
                    </div>
                    <div class="password">
                        <el-input v-model="password" style="width: 360px" type="password" placeholder="请再次输入密码"
                            show-password @blur="verifyPswAagin" />
                    </div>
                </div>
                <div class="btn-container">
                    <transition :name="transitionName" mode="out-in">
                        <div class="btn" @click="toLogin" v-if="flag" key="login">
                            立即登录
                        </div>
                        <div class="btn" @click="toRegister" v-else key="register">
                            注册
                        </div>
                    </transition>
                </div>
                <div class="check" @click="check">
                    {{ text }}
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { setToken } from '../../utils/setToken';
import { ElMessage } from 'element-plus'
import { register, login } from '../../api/api/login';
import { useRouter } from 'vue-router';

//实例化路由
const router = useRouter()

//全局变量
const formData = reactive({
    username: "",
    password: ""
})
const password = ref()

//切换登录/注册
const flag = ref(true)
const text = ref('还没账户？立即注册')
const transitionName = ref('slide-left')
const check = () => {
    //清空表单
    formData.password = ""
    formData.username = ""
    password.value = ""

    transitionName.value = flag.value ? 'slide-left' : 'slide-right'

    if (flag.value) {
        text.value = "已有账户？马上登录"
    } else {
        text.value = "还没账户？立即注册"
    }
    flag.value = !flag.value
}

//校验username
const verifyName = () => {
    //若输入框为空，返回false，不触发警告
    if (formData.username.length == 0) {
        return false
    }

    if (formData.username.length < 5) {
        //清空姓名框
        formData.username = ""

        ElMessage({
            type: "error",
            message: "用户名至少需要五个字符",
            duration: 1500
        })
        return false
    }
    return true
}

//校验密码
const verifyPsw = () => {
    //若输入框为空，返回false，不触发警告
    if (formData.password.length == 0) {
        return false
    }

    if (formData.password.length < 5) {
        //清空密码框
        formData.password = ""

        ElMessage({
            type: "error",
            message: "密码至少需要五个字符",
            duration: 1500
        })
        return false
    }
    return true
}

//校验重复密码
const verifyPswAagin = () => {
    //若输入框为空，返回false，不触发警告
    if (password.value.length == 0) {
        return false
    }

    if (formData.password != password.value) {
        //清空密码框
        formData.password = ""
        password.value = ""

        ElMessage({
            type: "error",
            message: "两次密码不相同，请重新输入",
            duration: 1500
        })
        return false
    }
    return true
}
//注册
const toRegister = () => {
    if (!verifyName() || !verifyPsw() || !verifyPswAagin()) {

        return
    }
    //注册
    register(formData)
        .then(res => {
            // 清空表单
            formData.password = ""
            formData.username = ""

            ElMessage({
                type: "success",
                message: "注册成功，请您登录!",
                duration: 1500
            })

            check()
        })
        .catch(err => {
            const message = err?.message || '注册失败！请重试'
            ElMessage({
                type: "error",
                message,
                duration: 1500
            })
        })
}
//登录
const toLogin = () => {
    if (!verifyName() || !verifyPsw()) {

        return
    }

    //登录
    login(formData)
        .then(res => {
            // 兼容接口字段
            const access = res.access || res.access_token || res.token
            const refresh = res.refresh || res.refresh_token
            const username = res.user?.username || res.username || formData.username

            if (!access) {
                throw new Error(res?.message || '登录失败，请稍后再试')
            }

            //清空表单
            formData.password = ""
            formData.username = ""
            //存储token
            const token = "Bearer" + " " + access
            setToken(token)
            if (refresh) {
                localStorage.setItem('refreshToken', refresh)
            }
            //存储用户名
            localStorage.setItem('user', username)
            ElMessage({
                type: "success",
                message: "登录成功，先锋小科欢迎您！",
                duration: 1500
            })

            // 立即跳转到对话页（hash 模式）
            router.push({ name: 'index' }).catch(() => {})
            // 兜底：如果路由未生效，强制修改 hash
            setTimeout(() => {
                if (!location.hash.includes('/index')) {
                    location.hash = '#/index'
                }
            }, 300)
        })
        .catch(err => {
            const message = err?.message || '登录失败！请重试'
            ElMessage({
                type: "error",
                message,
                duration: 1500
            })
        })
}
</script>

<style lang="scss" scoped>
.login {
    min-width: 100vw;
    min-height: 100vh;
    background: url('../../assets/loginbg.jpg') no-repeat center;
    background-size: cover;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;

    .loginBox {
        display: flex;
        align-items: center;
        width: 1113px;
        height: 538px;

        .boxLeft {
            height: 100%;
            width: 581px;

            img {
                width: 100%;
                height: 100%;
            }
        }

        .boxRight {
            flex: 1;
            height: 100%;
            background-color: #fff;
            border-radius: 12px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;

            .usernameInput,
            .passwordInput {
                display: flex;
                align-items: center;
                width: 414px;
                height: 40px;
                border: 1px solid #F5F5F5;
                border-radius: 4px;
            }

            .usernameInput {
                .userImage {
                    width: 20px;
                    height: 18px;
                    margin: 0 10px;

                    img {
                        width: 100%;
                        height: 100%;
                    }
                }

                .username {
                    :deep(.el-input__wrapper) {
                        box-shadow: 0 0 0 0;
                    }
                }
            }

            .passwordInput {
                margin-top: 20px;

                .passwordImage {
                    width: 20px;
                    height: 18px;
                    margin: 0 10px;

                    img {
                        width: 100%;
                        height: 100%;
                    }
                }

                .password {
                    :deep(.el-input__wrapper) {
                        box-shadow: 0 0 0 0;
                    }
                }
            }

            .btn-container {
                position: relative;
                width: 377px;
                height: 71px;
                margin-top: 70px;

                .slide-left-enter-active,
                .slide-left-leave-active,
                .slide-right-enter-active,
                .slide-right-leave-active {
                    transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
                    position: absolute;
                    width: 100%;
                }

                .slide-left-enter-from {
                    opacity: 0;
                    transform: translateX(30px);
                }

                .slide-left-leave-to {
                    opacity: 0;
                    transform: translateX(-30px);
                }

                .slide-right-enter-from {
                    opacity: 0;
                    transform: translateX(-30px);
                }

                .slide-right-leave-to {
                    opacity: 0;
                    transform: translateX(30px);
                }

                .btn {
                    position: absolute;
                    width: 100%;
                    height: 71px;
                    line-height: 71px;
                    text-align: center;
                    color: #fff;
                    background-color:#00569D;
                    border-radius: 12px;
                    cursor: pointer;
                    transition: all 0.3s ease;
                    will-change: transform;

                    &:hover {
                        filter: brightness(1.1);
                        box-shadow: 0 4px 20px rgba(27, 122, 85, 0.3);
                        transform: translateY(-2px);
                    }

                    &:active {
                        transform: translateY(1px);
                    }
                }
            }

            .check {
                transition: all 0.3s ease;
                font-size: 12px;
                margin-top: 10px;
                color: rgba(135, 135, 135, 0.57);
                cursor: pointer;

                &:hover {
                    transform: scale(1.05);
                    color: rgba(27, 122, 85, 0.8);
                }
            }
        }
    }
}
</style>
